<?

class FormProfileMain extends CFormModel{
    
    public $email;
    public $nick;
    public $name;
    public $lname;
    public $avatar;
    public $password_old;
    public $password_new;
    public $password_app;
    
    public function __construct($scenario=''){
        parent::__construct($scenario);
        if($USER = Yii::app()->user->getModel()){
            $this->email = $USER->email;
            $this->nick = $USER->nick;
            $this->name = $USER->name;
            $this->lname = $USER->lname;
            $this->avatar = $USER->avatar;
        }else{
            throw new CHttpException(403,'Forbidden');
        }
    }
    
    public function rules(){
        return array(
            array('email, nick, password_old', 'required'),
            array('avatar', 'file', 'allowEmpty'=>true, 'types'=>'jpg, gif, png', 'maxSize'=>2097152),
        );
    }
    
    public function attributeLabels(){
        return array(
            'email'=>UserModule::t('fields', 'Email'),
            'nick'=>UserModule::t('fields', 'Ник'),
            'name'=>UserModule::t('fields', 'Имя'),
            'lname'=>UserModule::t('fields', 'Фамилия'),
            'avatar'=>UserModule::t('fields', 'Аватар'),
            'password_old'=>UserModule::t('fields', 'Старый пароль'),
            'password_new'=>UserModule::t('fields', 'Новый пароль'),
            'password_app'=>UserModule::t('fields', 'Подтверждение нового пароля'),
        );
    }
    
    public function save(){
        $result = false;
        if($USER = Yii::app()->user->getModel()){
            if($USER->password == Users::CryptPassword($this->password_old)){
                $USER->avatar_old = $USER->avatar;
                
                $USER->email = $this->email;
                $USER->nick = $this->nick;
                $USER->name = $this->name;
                $USER->lname = $this->lname;
                $USER->avatar = $this->avatar;
                
                if(!empty($this->password_new) && $this->password_new == $this->password_app){
                    $USER->password = Users::CryptPassword($this->password_new);
                }else{
                    $this->addError('password_new', UserModule::t('app', 'Пароли не совпадают'));
                }
                
                $result = $USER->save();
            }else{
                $this->addError('password_old', UserModule::t('app', 'Старый пароль не совпадает'));
            }
        }else{
            throw new CHttpException(403,'Forbidden');
        }
        return $result;
    }
    
}
